﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace PK10Client
{
    class clientSocket
    {
        static void StartClient()
        {
            Socket clientSk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            SocketAsyncEventArgs ConnectSAE = new SocketAsyncEventArgs();
            ConnectSAE.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8596);
            ConnectSAE.Completed += new EventHandler<SocketAsyncEventArgs>(ConnectSAE_Completed);
            clientSk.ConnectAsync(ConnectSAE);
            Console.ReadLine();
        }

        static void ConnectSAE_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket clientSk = sender as Socket;
            if (e.SocketError == SocketError.Success && clientSk.Connected)
            {
                SocketAsyncEventArgs SendSAE = new SocketAsyncEventArgs();
                byte[] data = System.Text.Encoding.UTF8.GetBytes("I want put all funy things together!");
                SendSAE.SetBuffer(data, 0, data.Length);
                SendSAE.Completed += new EventHandler<SocketAsyncEventArgs>(SendSAE_Completed);

                SocketAsyncEventArgs RecieveSAE = new SocketAsyncEventArgs();
                byte[] buffer = new byte[2048];
                RecieveSAE.SetBuffer(buffer, 0, buffer.Length);
                RecieveSAE.Completed += new EventHandler<SocketAsyncEventArgs>(RecieveSAE_Completed);

                //先调用异步接收，再调用异步发送。让你体验到异步明显非一般的感觉。
                clientSk.ReceiveAsync(RecieveSAE);
                clientSk.SendAsync(SendSAE);
            }
        }

        static void RecieveSAE_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket sk = sender as Socket;
            byte[] data = e.Buffer;  //注意这里，如何取关联到套接字的发送接受的缓冲区中的值。
            string msg = System.Text.Encoding.UTF8.GetString(data);
            Console.WriteLine("Message received: " + msg);

            //sk.DisconnectAsync();//你看看 该怎么做呢？
        }

        static void SendSAE_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket sk = sender as Socket;
            if (e.SocketError == SocketError.Success)
            {
                Console.WriteLine("Send complete!");
            }
        }

    }
}
